package com.didi.virtualapk.hooker

import com.android.build.gradle.api.ApkVariant
import com.android.build.gradle.tasks.MergeSourceSetFolders
import com.android.ide.common.res2.AssetSet
import org.gradle.api.Project

import java.util.function.Predicate

/**
 * Remove the asset directory included in the excluded dependency before mergeAssets task
 *
 * @author zhengtao
 */
class MergeAssetsHooker extends GradleTaskHooker<MergeSourceSetFolders> {

    public MergeAssetsHooker(Project project, ApkVariant apkVariant) {
        super(project, apkVariant)
    }

    @Override
    String getTaskName() {
        return "merge${apkVariant.name.capitalize()}Assets"
    }

    /**
     * Remove the element(AssetSet) generated by the stripped dependenceInfos in the task inputDirectorySets
     * @param task Gradle task of mergeAssets
     */
    @Override
    void beforeTaskExecute(MergeSourceSetFolders task) {

        Set<String> retainedAssetPaths = virtualApk.retainedAarLibs.collect {
            it.assetsFolder.path
        }

        List<AssetSet> assetSets = task.inputDirectorySets
        assetSets.removeIf(new Predicate<AssetSet>() {
            @Override
            boolean test(AssetSet assetSet) {
                return !retainedAssetPaths.contains(assetSet.sourceFiles.get(0).path)
            }
        })

        task.inputDirectorySets = assetSets
    }

    @Override
    void afterTaskExecute(MergeSourceSetFolders task) {
    }
}